<template>
	<view class="step-one-container">
		<view class="tips-box">
			<view class="font-18 col-000-8 font-600">
				<!-- 选择您的设备 -->
				{{$t('addDevice.selectYourDevice')}}
			</view>
			<view class="font-14 col-000-4 m-t-8">
				<!-- 请确保您的沙画设备已开机并处于配置模式 -->
				{{$t('addDevice.tipsOne')}}
				<span class="col-3C82F6">{{$t('addDevice.configMode')}}</span>
			</view>
		</view>
		<view class="device-box">
			<view class="round">
				<image class="img" src="/static/svg/devices.svg" mode="widthFix"></image>
			</view>
			<view class="round-run animate-ping" v-if="isScanning">
			</view>
		</view>
		
		<!-- 蓝牙权限提示 -->
		<view class="wifi-tips" v-if="!bluetoothEnabled">
			<view class="tips-content">
				<uni-icons type="info" size="20" color="#FF6B6B"></uni-icons>
				<text class="tips-text">{{$t('addDevice.pleaseTurnOnBluetooth')}}</text>
			</view>
		</view>
		
		<!-- 扫描状态提示 -->
		<view class="scan-status" v-if="isScanning">
			<view class="status-content">
				<uni-icons type="loop" size="16" color="#3C82F6"></uni-icons>
				<text class="status-text">
					{{$t('addDevice.searchingDevices')}}
					<span v-if="scanConfig.currentRetry > 0">({{$t('addDevice.retry')}} {{scanConfig.currentRetry}}/{{scanConfig.maxRetries}})</span>
				</text>
			</view>
		</view>
		
		<view class="devices-list">
			<view class="item" v-for="(item, index) in devicesList" :key="index">
				<view class="left">
					<view class="img">
						<image class="img-100" v-if="item.status === 1" src="/static/svg/devices.svg" mode="widthFix"></image>
						<image class="img-100" v-else src="/static/svg/devices-000.svg" mode="widthFix"></image>
					</view>
					<view class="name-box">
						<view class="name col-000-8 font-16 font-500">
							{{item.name}}
						</view>
						<view class="online font-12 col-000-4">
							{{$t('addDevice.signalstrength')}}: <text
								:class="'online-' + item.signalLevel">{{getSignalText(item.signalLevel)}}</text>
						</view>
					</view>
				</view>
				<view class="status font-14 col-3C82F6" @click="doConcat(item.deviceId, item.status)">
					<text v-if="connectingDeviceId === item.deviceId">{{$t('addDevice.connecting')}}</text>
					<text v-else>{{item.status == 1 ? $t('addDevice.connected') : $t('addDevice.connect')}}</text>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<view class="empty-devices" v-if="!isScanning && devicesList.length === 0">
				<view class="empty-content">
					<uni-icons type="search" size="48" color="#CCCCCC"></uni-icons>
					<text class="empty-text">{{$t('addDevice.noDevicesFound')}}</text>
					<text class="empty-tips">{{$t('addDevice.ensureDeviceOn')}}</text>
				</view>
			</view>
		</view>
		
		<view class="refresh-box-zan"></view>
		<view class="refresh-box flex-center-center font-20 col-000-8" @click="refreshDevices">
			<uni-icons style="margin-right: 10px;" type="loop" size="30" :class="{ 'rotate-icon': isScanning }"></uni-icons>
			{{isScanning ? $t('addDevice.scanning') : $t('addDevice.Refresh')}}
		</view>
	</view>
</template>

<script>
	export default {
		emits: ['doConcat', 'deviceSelected'],
		data() {
			return {
				// 蓝牙相关状态
				bluetoothEnabled: false, // 蓝牙是否开启
				isScanning: false, // 是否正在扫描
				scanTimer: null, // 扫描定时器
				devicesList: [], // 设备列表
				discoveredDevices: new Map(), // 已发现的设备 Map，防重复
				connectingDeviceId: '', // 正在连接的设备ID
				
				// 扫描配置
				scanConfig: {
					scanDuration: 15000, // 扫描持续时间(毫秒)
					maxRetries: 3, // 最大重试次数
					currentRetry: 0 // 当前重试次数
				}
			}
		},
		
		mounted() {
			console.log('[BLE] 组件挂载，开始初始化蓝牙扫描')
			this.initBluetoothScan()
		},
		
		beforeDestroy() {
			console.log('[BLE] 组件销毁，清理蓝牙扫描资源')
			this.cleanupBluetoothScan()
		},
		
		methods: {
			/**
			 * 初始化蓝牙扫描功能
			 */
			async initBluetoothScan() {
				try {
					console.log('[BLE] 开始初始化蓝牙扫描')
					
					// 初始化蓝牙适配器
					await this.initBluetoothAdapter()
					
					// 自动开始扫描
					this.startBluetoothScan()
					
				} catch (error) {
					console.error('[BLE] 初始化蓝牙扫描失败:', error)
					
					let errorMessage = '蓝牙初始化失败'
					if (error.errCode === 10001) {
						errorMessage = '请先打开蓝牙'
					} else if (error.errMsg) {
						errorMessage = error.errMsg
					}
					
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 3000
					})
				}
			},
			
			/**
			 * 初始化蓝牙适配器
			 */
			async initBluetoothAdapter() {
				return new Promise((resolve, reject) => {
					console.log('[BLE] 初始化蓝牙适配器')
					
					uni.openBluetoothAdapter({
						success: (res) => {
							console.log('[BLE] 蓝牙适配器初始化成功:', res)
							this.bluetoothEnabled = true
							resolve(res)
						},
						fail: (error) => {
							console.error('[BLE] 蓝牙适配器初始化失败:', error)
							this.bluetoothEnabled = false
							
							if (error.errCode === 10001) {
								reject({ errCode: 10001, errMsg: '请先打开蓝牙' })
							} else {
								reject(error)
							}
						}
					})
				})
			},
			
			/**
			 * 开始蓝牙设备扫描
			 */
			startBluetoothScan() {
				if (this.isScanning) {
					console.log('[BLE] 已在扫描中，跳过')
					return
				}
				
				console.log('[BLE] 开始扫描蓝牙设备')
				this.isScanning = true
				this.scanConfig.currentRetry = 0
				
				// 清空之前的设备列表
				this.devicesList = []
				this.discoveredDevices.clear()
				
				// 监听设备发现事件
				uni.onBluetoothDeviceFound(this.onBluetoothDeviceFound)
				
				// 开始扫描
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false, // 不允许重复上报同一设备
					success: (res) => {
						console.log('[BLE] 开始扫描成功:', res)
						
						// 设置扫描超时
						this.scanTimer = setTimeout(() => {
							this.stopBluetoothScan()
							
							// 如果没有发现设备，提示用户
							if (this.devicesList.length === 0) {
								uni.showToast({
									title: '未发现设备，请确保设备已开机',
									icon: 'none',
									duration: 2000
								})
							}
						}, this.scanConfig.scanDuration)
					},
					fail: (error) => {
						console.error('[BLE] 开始扫描失败:', error)
						this.isScanning = false
						
						let errorMessage = '蓝牙扫描失败'
						if (error.errCode === 10001) {
							errorMessage = '请先打开蓝牙'
						}
						
						uni.showToast({
							title: errorMessage,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			
			/**
			 * 蓝牙设备发现回调
			 */
			onBluetoothDeviceFound(res) {
				console.log('[BLE] 发现蓝牙设备:', res)
				console.log('[BLE] 设备数量:', res.devices ? res.devices.length : 0)
				
				if (!res.devices || res.devices.length === 0) {
					return
				}
				
				res.devices.forEach(device => {
					console.log('[BLE] 设备详情:', {
						name: device.name,
						localName: device.localName,
						deviceId: device.deviceId,
						RSSI: device.RSSI,
						advertisData: device.advertisData,
						advertisServiceUUIDs: device.advertisServiceUUIDs
					})
					
					// 打印所有设备名称，方便调试
					if (device.name) {
						console.log(`[BLE] 发现设备名称: "${device.name}"`)
					}
					if (device.localName) {
						console.log(`[BLE] 发现设备本地名称: "${device.localName}"`)
					}
					
					// 过滤 sandart 开头的设备 (同时检查 name 和 localName)
					const deviceName = (device.name || device.localName || '').toLowerCase()
					console.log(`[BLE] 检查设备名称: "${deviceName}"`)
					
					if (deviceName.startsWith('sandart')) {
						console.log(`[BLE] ✅ 匹配到 Sandart 设备: ${deviceName}`)
						this.processDiscoveredBluetoothDevice(device)
					} else if (deviceName) {
						console.log(`[BLE] ❌ 设备名称不匹配: "${deviceName}"`)
					} else {
						console.log(`[BLE] ⚠️ 设备没有名称`)
					}
				})
			},
			
			/**
			 * 处理发现的蓝牙设备
			 */
			processDiscoveredBluetoothDevice(device) {
				console.log('[BLE] 发现 Sandart 设备:', device)
				
				// 防止重复添加
				if (this.discoveredDevices.has(device.deviceId)) {
					// 更新信号强度
					const existingDevice = this.discoveredDevices.get(device.deviceId)
					existingDevice.signalStrength = device.RSSI
					existingDevice.signalLevel = this.calculateSignalLevel(device.RSSI)
					return
				}
				
				// 计算信号强度等级
				const signalLevel = this.calculateSignalLevel(device.RSSI)
				
				// 创建设备对象
				const deviceInfo = {
					id: device.deviceId,
					deviceId: device.deviceId,
					name: device.name || device.localName || this.$t('addDevice.sandDevice'),
					status: 2, // 2表示未连接，1表示已连接
					statusName: this.$t('addDevice.connect'),
					signalLevel: signalLevel,
					signalStrength: device.RSSI,
					advertisData: device.advertisData,
					discoveredAt: new Date().getTime()
				}
				
				// 添加到已发现设备Map
				this.discoveredDevices.set(device.deviceId, deviceInfo)
				
				// 添加到设备列表
				this.devicesList.push(deviceInfo)
				
				console.log('[BLE] 已添加 Sandart 设备到列表:', deviceInfo)
			},
			
			/**
			 * 计算信号强度等级
			 * @param {number} rssi 信号强度值
			 * @returns {number} 信号等级 1-强 2-中 3-弱
			 */
			calculateSignalLevel(rssi) {
				if (rssi >= -50) {
					return 1 // 强信号
				} else if (rssi >= -70) {
					return 2 // 中等信号
				} else {
					return 3 // 弱信号
				}
			},
			
			/**
			 * 获取信号强度文本
			 */
			getSignalText(level) {
				const signalTexts = {
					1: this.$t('addDevice.good'),
					2: this.$t('addDevice.fair'), 
					3: this.$t('addDevice.poor')
				}
				return signalTexts[level] || this.$t('addDevice.poor')
			},
			
			/**
			 * 停止蓝牙扫描
			 */
			stopBluetoothScan() {
				if (!this.isScanning) {
					return
				}
				
				console.log('[BLE] 停止蓝牙扫描')
				this.isScanning = false
				
				// 清除定时器
				if (this.scanTimer) {
					clearTimeout(this.scanTimer)
					this.scanTimer = null
				}
				
				// 停止扫描
				uni.stopBluetoothDevicesDiscovery({
					success: () => {
						console.log('[BLE] 停止扫描成功')
					},
					fail: (error) => {
						console.log('[BLE] 停止扫描失败:', error)
					}
				})
			},
			
			/**
			 * 刷新设备列表
			 */
			refreshDevices() {
				if (this.isScanning) {
					console.log('[BLE] 正在扫描中，无法刷新')
					return
				}
				
				console.log('[BLE] 手动刷新设备列表')
				this.startBluetoothScan()
			},
			
			/**
			 * 清理蓝牙扫描资源
			 */
			cleanupBluetoothScan() {
				try {
					// 停止扫描
					this.stopBluetoothScan()
					
					// ⚠️ 注意：不要关闭蓝牙适配器！
					// 因为 step-two 还需要使用蓝牙连接来发送 WiFi 配置
					// 蓝牙适配器应该在整个添加设备流程结束后才关闭
					// uni.closeBluetoothAdapter() 已移除
					
					console.log('[BLE] 蓝牙扫描已停止（保持蓝牙适配器开启）')
				} catch (error) {
					console.error('[BLE] 清理蓝牙扫描资源时发生错误:', error)
				}
			},
			
			/**
			 * 连接设备处理
			 */
			async doConcat(deviceId, status) {
				if (status == 1) {
					console.log('[BLE] 设备已连接，无需重复连接')
					return
				}
				
				// 防止重复连接
				if (this.connectingDeviceId === deviceId) {
					console.log('[BLE] 正在连接中，请勿重复点击')
					return
				}
				
				console.log('[BLE] 尝试连接蓝牙设备:', deviceId)
				
				// 设置连接状态
				this.connectingDeviceId = deviceId
				
				// 停止扫描
				this.stopBluetoothScan()
				
				// 获取设备信息
				const deviceInfo = this.discoveredDevices.get(deviceId)
				
				// 尝试连接到蓝牙设备
				await this.connectToBluetoothDevice(deviceId, deviceInfo)
				
				// 清除连接状态
				this.connectingDeviceId = ''
			},
			
			/**
			 * 连接到蓝牙设备
			 */
			async connectToBluetoothDevice(deviceId, deviceInfo) {
				try {
					console.log('[BLE] 开始连接到蓝牙设备:', deviceId)
					
					uni.showLoading({
						title: '正在连接设备...',
						mask: true
					})
					
					// 创建BLE连接
					await this.createBLEConnection(deviceId)
					
					console.log('[BLE] 蓝牙连接成功')
					
					// 更新设备状态为已连接
					if (deviceInfo) {
						deviceInfo.status = 1
						deviceInfo.statusName = '已连接'
						
						// 更新设备列表中的状态
						const deviceIndex = this.devicesList.findIndex(device => device.deviceId === deviceId)
						if (deviceIndex !== -1) {
							this.$set(this.devicesList, deviceIndex, { ...deviceInfo })
						}
					}
					
					uni.hideLoading()
					
					uni.showToast({
						title: '连接成功',
						icon: 'success',
						duration: 1500
					})
					
					// 延迟发射事件，让用户看到连接成功状态
					setTimeout(() => {
						// 发射设备选中事件给父组件
						this.$emit('deviceSelected', deviceInfo)
						
						// 发送连接事件给父组件，切换到下一步
						this.$emit('doConcat', 1)
					}, 1500)
					
				} catch (error) {
					console.error('[BLE] 蓝牙连接失败:', error)
					
					uni.hideLoading()
					
					let errorMessage = '连接失败，请重试'
					if (error.errCode === 10001) {
						errorMessage = '请先打开蓝牙'
					} else if (error.errCode === 10003) {
						errorMessage = '连接失败，请靠近设备后重试'
					} else if (error.errCode === 10006) {
						errorMessage = '当前连接已断开'
					} else if (error.errMsg) {
						errorMessage = error.errMsg
					}
					
					uni.showToast({
						title: errorMessage,
						icon: 'none',
						duration: 2000
					})
				} finally {
					this.connectingDeviceId = ''
				}
			},
			
			/**
			 * 创建BLE连接
			 */
			async createBLEConnection(deviceId) {
				return new Promise((resolve, reject) => {
					uni.createBLEConnection({
						deviceId: deviceId,
						timeout: 10000, // 10秒超时
						success: (res) => {
							console.log('[BLE] 创建BLE连接成功:', res)
							resolve(res)
						},
						fail: (error) => {
							console.error('[BLE] 创建BLE连接失败:', error)
							reject(error)
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.step-one-container {
		width: 100%;
		position: relative;
	}

	.refresh-box-zan {
		width: 100%;
		height: 110rpx;
	}
	
	.refresh-box {
		width: 700rpx;
		height: 100rpx;
		border-radius: 16rpx;
		border: 1px solid rgba(0,0,0,0.8);
		margin: 0 auto;
		position: fixed;
		left: 50%;
		transform: translateX(-50%);
		bottom: 20rpx;
		background-color: #fff;
		transition: all 0.3s ease;
		
		&:active {
			transform: translateX(-50%) scale(0.98);
		}
	}
	
	// 旋转动画
	.rotate-icon {
		animation: rotate 1s linear infinite;
	}
	
	@keyframes rotate {
		from {
			transform: rotate(0deg);
		}
		to {
			transform: rotate(360deg);
		}
	}
	
	// WiFi权限提示
	.wifi-tips {
		width: 100%;
		margin: 20rpx 0;
		
		.tips-content {
			background: rgba(255, 107, 107, 0.1);
			border: 1rpx solid rgba(255, 107, 107, 0.3);
			border-radius: 12rpx;
			padding: 24rpx 32rpx;
			display: flex;
			align-items: center;
			
			.tips-text {
				margin-left: 16rpx;
				font-size: 28rpx;
				color: #FF6B6B;
			}
		}
	}
	
	// 扫描状态提示
	.scan-status {
		width: 100%;
		margin: 20rpx 0;
		
		.status-content {
			background: rgba(60, 130, 246, 0.1);
			border: 1rpx solid rgba(60, 130, 246, 0.3);
			border-radius: 12rpx;
			padding: 20rpx 32rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			
			.status-text {
				margin-left: 12rpx;
				font-size: 26rpx;
				color: #3C82F6;
			}
		}
	}
	
	// 空状态样式
	.empty-devices {
		width: 100%;
		padding: 80rpx 0;
		
		.empty-content {
			text-align: center;
			
			.empty-text {
				display: block;
				margin-top: 24rpx;
				font-size: 32rpx;
				color: #999;
				font-weight: 500;
			}
			
			.empty-tips {
				display: block;
				margin-top: 16rpx;
				font-size: 24rpx;
				color: #CCC;
			}
		}
	}
	
	.devices-list {
		width: 100%;
		margin: 80rpx auto 0;

		.item {
			padding: 28rpx 32rpx;
			background: #FFFFFF;
			box-shadow: 0px 0px 8rpx 0px rgba(0, 0, 0, 0.08);
			border-radius: 16rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-bottom: 16rpx;
			transition: all 0.3s ease;

			&:active {
				transform: scale(0.98);
			}

			.left {
				display: flex;
				align-items: center;
				justify-content: flex-start;
			}

			.img {
				width: 44rpx;
				min-width: 44rpx;
				height: 32rpx;
				margin-right: 34rpx;
			}

			.name-box {
				max-width: 300rpx;

				.online {
					margin-top: 8rpx;
				}
				
				.device-info {
					margin-top: 4rpx;
					opacity: 0.8;
				}
			}

			.online-1 {
				color: #30A44F;
			}

			.online-2 {
				color: #FABD18;
			}

			.online-3 {
				color: #FF4D4F;
			}
			
			.status {
				padding: 12rpx 24rpx;
				border-radius: 8rpx;
				border: 1rpx solid #3C82F6;
				background: rgba(60, 130, 246, 0.1);
				transition: all 0.3s ease;
				
				&:active {
					background: rgba(60, 130, 246, 0.2);
				}
			}
		}
	}

	.device-box {
		width: 100%;
		margin: 80rpx auto 0;
		display: flex;
		justify-content: center;
		align-items: center;
		position: relative;
		height: 180rpx;

		.round {
			width: 140rpx;
			height: 140rpx;
			border-radius: 100%;
			background-color: rgba(60, 130, 246, 0.15);
			display: flex;
			justify-content: center;
			align-items: center;
			margin: auto 0;

			.img {
				width: 60rpx;
				height: 44rpx;
			}

			position: absolute;
			left: 50%;
			top: 50%;
			z-index: 2;
			transform: translate(-50%, -50%);
		}

		.round-run {
			width: 180rpx;
			height: 180rpx;
			border-radius: 100%;
			background-color: rgba(60, 130, 246, 0.15);
			position: absolute;
			left: 50%;
			top: 50%;
			z-index: 1;
			transform: translate(-50%, -50%);
		}
	}

	.tips-box {
		width: 100%;
		margin-top: 80rpx;
	}

	@keyframes ping {
		0% {
			transform: translate(-50%, -50%) scale(1);
			opacity: 1;
		}

		75%,
		100% {
			transform: translate(-50%, -50%) scale(1.7);
			opacity: 0;
		}
	}

	.animate-ping {
		animation: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite;
	}
	
	// 暗色模式适配
	@media (prefers-color-scheme: dark) {
		.refresh-box {
			background-color: #1c1c1e;
			border-color: rgba(255, 255, 255, 0.3);
			color: #fff;
		}
		
		.devices-list .item {
			background: #2c2c2e;
			color: #fff;
			
			.status {
				border-color: #007AFF;
				background: rgba(0, 122, 255, 0.2);
			}
		}
		
		.wifi-tips .tips-content,
		.scan-status .status-content {
			background: rgba(0, 0, 0, 0.5);
		}
		
		.empty-devices .empty-content {
			.empty-text {
				color: #8E8E93;
			}
			
			.empty-tips {
				color: #636366;
			}
		}
	}
</style>